<?php
namespace plugins\department\model;

use plugins\user\model\UserModel;
use think\Db;
use think\Model;

/**
 * 地址模型
 */
class DepartmentModel extends Model
{

    /**
     * 利用递归法获取无限极类别的树状数组
     */
    function arrayTree($array, $pid =0, $id=''){
        //声明静态数组,避免递归调用时,多次声明导致数组覆盖
        $list = [];

        foreach ($array as $key => $value){
            //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
            if ($value['parent_id'] == $pid){
                //父节点为根节点的节点,级别为0，也就是第一级
                $value['label'] = $value['name'];
                $value['value'] = $value['id'];

                if(!empty($id) && $id == $value['id']){
                    $value['disabled'] = true;
                }
                //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                $children = $this->arrayTree($array,$value['id'],$id );
                if(!empty($children)){
                    $value['children'] = $children;
                }
                //把数组放到list中
                $list[] = $value;
            }
        }
        return $list;
    }

    public function getLowLevel($id){
        $id_arr = [];
        $list = $this->where('parent_id',$id)->select();
        foreach ($list as $item){
            $id_arr[] = $item['id'];
            $children = $this->getLowLevel($item['id']);
            $id_arr = array_merge($id_arr,$children);
        }
        return $id_arr;
    }

    /**
     * 部门详细信息
     */
    function getDepartmentDetail($item){
        $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
        $item['edit_time'] = date('Y-m-d H:i:s',$item['edit_time']);
        //创建人名称
        $user_name = '-';
        $user = Db::name('user')->where('id',$item['create_uid'])->find();
        if(!empty($user)){
            $user_name = $user['user_login'];
        }
        $item['user_name'] = $user_name;
        //上级部门
        $parent_name = '-';
        $department = $this->where('id',$item['parent_id'])->find();
        if(!empty($department)){
            $parent_name = $department['name'];
        }
        $item['parent_name'] = $parent_name;
        //地区名称
        $address_name = '-';
        $address = Db::name('address')->where('cri_code',$item['address_id'])->find();
        if(!empty($address)){
            $address_name = $address['cri_name'];
        }
        $item['address_name'] = $address_name;
        //部门人数
        $userModel = new UserModel();
        $ids_arr = $this->getLowLevel($item['id']);
        $ids_arr[] = $item['id'];
        $where = [];
        foreach ($ids_arr as $id_item){
            $where['department_id'][] = ['=',$id_item];
        }
        if(!empty($where['department_id'])){
            $where['department_id'][] = 'or';
        }

        $department_num = $userModel->where($where)->count();
        $item['department_num'] = $department_num;

        return $item;
    }
}
